package com.example.chatweb.controller;

import com.example.chatweb.request.UploadChatHubRequest;
import com.example.chatweb.service.KnowledgeBaseService;
import com.example.chatweb.utils.MyExceptionHandler;
import com.example.chatweb.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@CrossOrigin(origins = "*")
@RestController
@Slf4j
public class KnowledgeBaseController {
	
	private final KnowledgeBaseService knowledgeBaseService;
	
	@Autowired
	public KnowledgeBaseController(KnowledgeBaseService knowledgeBaseService) {
		this.knowledgeBaseService = knowledgeBaseService;
	}
	
	@PostMapping(value = "/create_knowledge_base")
	public R createKnowledgeBase(@RequestBody UploadChatHubRequest uploadChatHubRequest) {
		if (uploadChatHubRequest.getKnowledge_base_name() == null
		 || uploadChatHubRequest.getKnowledge_base_name().isEmpty()) {
			return R.failure("知识库名称不能为空");
		}
		try {
			knowledgeBaseService.createKnowledgeBase(uploadChatHubRequest.getKnowledge_base_name());
			return R.ok();
		} catch (MyExceptionHandler e) {
			return R.failure(e.getMessage());
		}
	}
	
	@PostMapping(value = "/upload_chat_hub")
	public R uploadChatHub(@RequestBody UploadChatHubRequest uploadChatHubRequest) {
		if (uploadChatHubRequest.getKnowledge_base_name() == null
		 || uploadChatHubRequest.getKnowledge_base_name().isEmpty()) {
			return R.failure("知识库名称不能为空");
		}
		if (uploadChatHubRequest.getUrl() == null || uploadChatHubRequest.getUrl().isEmpty()) {
			return R.failure("URL不能为空");
		}
		try {
			// 先创建知识库
			knowledgeBaseService.createKnowledgeBase(uploadChatHubRequest.getKnowledge_base_name());
			
			//	下载URL后向量化
			knowledgeBaseService.addFileToKnowledgeBase(uploadChatHubRequest.getUrl(),
			 uploadChatHubRequest.getKnowledge_base_name());
			return R.ok();
		} catch (MyExceptionHandler e) {
			log.error("捕获到异常", e);
			return R.failure(e.getMessage());
		} catch (Exception e) {
			log.error("捕获到未知异常", e);
			return R.failure(e.getMessage());
		}
	}
	
}
